from rest_framework.viewsets import ModelViewSet
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from app01.models import Book


def check_author(data):
    if data.startswith('sb'):
        raise ValidationError('你才是sb')
    return data


class BookSerializer(serializers.Serializer):
    id = serializers.CharField(read_only=True)
    name = serializers.CharField(max_length=32, min_length=3)
    price = serializers.CharField(write_only=True)
    author = serializers.CharField(validators=[check_author])  # validators里放函数内存地址
    publish = serializers.CharField()

    # 局部钩子
    def validate_price(self, data):
        # 如果价格小于10 就校验不通过
        print(type(data), data)
        if float(data) > 10:
            return data
        else:
            raise ValidationError('价格太低')

    def validate(self, validated_data):
        print(validated_data)
        # OrderedDict([('name', '三国演义'), ('price', '20'), ('author', '罗贯中'), ('publish', '南京出版社')])
        author = validated_data.get('author')
        publish = validated_data.get('publish')
        if author == publish:
            raise ValidationError('哪有作者名跟出版社名字一样的书')
        return validated_data

    def update(self, instance, validated_data):
        """

        :param instance: book对象
        :param validated_data: 校验后的数据
        :return: 实例对象
        """
        instance.name = validated_data.get('name')
        instance.price = validated_data.get('price')
        instance.author = validated_data.get('author')
        instance.publish = validated_data.get('publish')
        instance.save()  # book.save  django 的orm提供的
        return instance

    def create(self, validated_data):
        print('data:', validated_data)
        # data: {'name': '社会民求偶之旅', 'price': '30', 'author': '社会斌', 'publish': '北京出版社'}
        instance = Book.objects.create(**validated_data)
        return instance


# 模型序列化器 不需要重写里面的方法了
class BookModelSerializer(serializers.ModelSerializer):
    # 局部钩子
    def validate_price(self, data):
        # 如果价格小于10 就校验不通过
        print(type(data), data)
        if float(data) > 10:
            return data
        else:
            raise ValidationError('价格太低')

    class Meta:
        model = Book
        fields = '__all__'  # 所有字段都要序列化
        # fields = ('name', 'price')  # 指定需要序列化的字段
        # exclude = (['name'])  # 只有name字段不要序列化
        read_only_fields = ('price', )
        # write_only_fields = ('author', )  # 不支持这种写法 忘了吧

        # 给字段添加额外属性(校验)

        extra_kwargs = {
            'author': {'write_only': True, 'min_length': 2},
        }
